#!/bin/bash

# cat > /etc/systemd/system/controller_cpu.servic <<EOF
# [Unit]
# Description=Controller CPU Service
# After=network.target

# [Service]
# ExecStart=/usr/local/bin/controller_cpu.sh 30 50
# Restart=always
# User=root
# Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# [Install]
# WantedBy=multi-user.target
# EOF

# sudo systemctl daemon-reload
# sudo systemctl start controller_cpu.service
# sudo systemctl enable controller_cpu.service


# 检查是否提供了参数
if [ "$#" -ne 1 ]; then
  echo "用法: $0 <最大值>"
  exit 1
fi

# 获取参数
MAX_VALUE=$1
# 循环次数
COUNTER=1
# 定义程序路径
PROGRAM="./cpu_consumer_linux"

# 定义清理函数，在脚本结束时关闭程序
cleanup() {
  pkill -f $PROGRAM
}

# 捕获脚本结束信号并调用清理函数
trap cleanup EXIT

while true; do
  # 获取当前时间
  LOG_TIME="[$(date '+%Y-%m-%d %H:%M:%S')]"
  # 生成随机的 -u 参数值
  #U_VALUE=$((RANDOM % (MAX_VALUE - 10 + 1) + 10))  
  U_VALUE1=$((MAX_VALUE / 3 + 10)) 


  RUN_TIME=$((RANDOM % 3 + 1))
  if [[ $COUNTER == $RUN_TIME ]]; then
    kill $PROGRAM_PID3
    PROGRAM_PID3=""
    # 启动程序3并输出日志
    echo "${LOG_TIME} 启动程序3..."
    $PROGRAM -u $U_VALUE1 &
    PROGRAM_PID3=$!  
    COUNTER=0
  else
    ((COUNTER++))
  fi

  # 启动程序1并输出日志
  echo "${LOG_TIME} 启动程序1..."
  $PROGRAM -u $U_VALUE1 &
  PROGRAM_PID1=$!  

  RUN_TIME=$((RANDOM % 60 + 10))
  sleep ${RUN_TIME}s

  # 启动程序2并输出日志
  echo "${LOG_TIME} 启动程序2..."
  $PROGRAM -u $U_VALUE1 &
  PROGRAM_PID2=$!

  RUN_TIME=$((RANDOM % 120 + 10))
  sleep ${RUN_TIME}s

  # 关闭程序1
  echo "${LOG_TIME} 关闭程序1..."
  kill $PROGRAM_PID1
  PROGRAM_PID1=""

  RUN_TIME=$((RANDOM % 120 + 10))
  sleep ${RUN_TIME}s

  # 关闭程序2
  echo "${LOG_TIME} 关闭程序2..."
  kill $PROGRAM_PID2
  PROGRAM_PID2=""

  RUN_TIME=$((RANDOM % 120 + 10))
  sleep ${RUN_TIME}s
done